﻿using NPoco;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;

namespace ServiceKit
{
    /// <summary>
    /// 数据库设置
    /// </summary>
    public class DBConfig
    {
        private static Dictionary<string, DatabaseFactory> _dbFactorys = new Dictionary<string, DatabaseFactory>();

        public static DatabaseFactory Factory(string dbName = "Default")
        {
            DatabaseFactory factory = null;
            if (!_dbFactorys.TryGetValue(dbName, out factory))
            {
                ConnectionStringsConfig config = ServerUtil.Configuration.GetSection("ConnectionString").Get<ConnectionStringsConfig>();
                switch (config.ProviderName)
                {
                    case "MySQL":
                        factory = DatabaseFactory.Config(x =>
                        {
                            x.UsingDatabase(() => new WonderDataBase(config.ConnectionString, DatabaseType.MySQL, MySqlClientFactory.Instance));
                        });
                        break;
                    case "SqlServer2012":
                        factory = DatabaseFactory.Config(x =>
                        {
                            x.UsingDatabase(() => new WonderDataBase(config.ConnectionString, DatabaseType.SqlServer2012, SqlClientFactory.Instance));
                        });
                        break;
                    default:
                        break;
                }
                _dbFactorys.Add(dbName, factory);
            }
            return factory;
        }
    }

    public class ConnectionStringsConfig
    {
        public string ProviderName { get; set; }
        public string ConnectionString { get; set; }
    }
}
